import 'package:async/async.dart';
import 'package:boss/color_constant.dart';
import 'package:boss/main.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/widget/calendar/util/date_util.dart';
import 'package:boss/ui/widget/calendar_bar.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/loader/loader_pull_refresh.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flustars/flustars.dart' as flustars;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class ClerkCashierPageIndex extends StatefulWidget {
  ClerkCashierPageIndex({Key key}) : super(key: key);

  @override
  ClerkCashierPageIndexState createState() => ClerkCashierPageIndexState();
}

class ClerkCashierPageIndexState extends State<ClerkCashierPageIndex> {
  final GlobalKey<LoaderPullRefreshState> loaderPullRefreshKey = GlobalKey<LoaderPullRefreshState>();

  DateTime startTime;

  DateTime endTime;

  dynamic acceptData;

  //折叠bool
  bool boolFold0 = false;
  bool boolFold1 = false;

  List<dynamic> tableData = [];

  RefreshController _refreshController;

  @override
  void initState() {
    super.initState();
    _refreshController = RefreshController(initialRefresh: false);

    final now = DateTime.now();

    startTime = DateUtils.startOfTheDay(now);
    endTime = DateUtils.endOfTheDay(now);
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  refresh({bool needMove = true}) async {
    await _refreshController.requestRefresh(
      needMove: needMove,
      duration: Duration(milliseconds: 100),
    );
  }

  String dateTime2String(DateTime dateTime) {
    return flustars.DateUtil.formatDate(dateTime);
  }

  //发送邮箱
  sendMailbox(String e) async {
    showLoadingToast();
    try {
      var res = await api.sendEmailWithUserCashSumDataReport(
        startTime: dateTime2String(startTime),
        endTime: dateTime2String(endTime),
        email: e ?? '',
      );
      if (res.successful()) {
        toast("邮箱发送成功!");
        Navigator.pop(context);
      } else {
        toast(res.msg);
      }
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  //蓝色块
  Widget bottomItem(String title, dynamic value, String unit) {
    return Container(
      child: Column(
        children: <Widget>[
          value is Widget
              ? value
              : Text(
                  "$value",
                  style: TextStyleConstant().white_36,
                ),
          RichText(
            text: TextSpan(children: <TextSpan>[
              TextSpan(
                text: '$title/',
                style: TextStyle(
                  fontSize: 24.sp,
                  color: Color.fromRGBO(255, 255, 255, .8),
                ),
              ),
              TextSpan(
                text: '$unit',
                style: TextStyleConstant().yellow_22,
              ),
            ]),
          ),
        ],
      ),
    );
  }

  Widget blueTitleBottomItem() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Expanded(flex: 1, child: bottomItem('    合计', '${acceptData == null ? 0 : acceptData["totalOrderCount"] ?? 0}', '单    ')),
        line(),
        Expanded(
          flex: 1,
          child: bottomItem('优惠金额', discountAmount(acceptData == null ? 0 : acceptData["discountAmount"]), '元'),
        ),
        line(),
        Expanded(flex: 1, child: bottomItem('订单金额', discountAmount(acceptData == null ? 0 : acceptData["totalOrderAmount"]), '元')),
        line(),
        Expanded(flex: 1, child: bottomItem('小费金额', discountAmount(acceptData == null ? 0 : acceptData["totalTip"]), '元')),
      ],
    );
  }

  Widget line() {
    return Padding(
      padding: EdgeInsets.only(
        left: ScreenUtil.instance.setWidth(2),
        right: ScreenUtil.instance.setWidth(2),
      ),
      child: Container(
        width: .6,
        height: 68.w,
        color: Colors.white,
      ),
    );
  }

  //实收金额标题
  Widget totalInComeAmount() {
    String money = (AmountUtil.price2String(
      (acceptData == null ? 0 : acceptData["totalInComeAmount"]) ?? 0,
    ));
    String money1 = '00';
    String money0 = money.split(".")[0];
    if (money.split('.').length > 1) {
      money1 = money.split(".")[1];
    }

    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          RichText(
              text: TextSpan(children: <TextSpan>[
            TextSpan(
              text: '¥ ',
              style: TextStyle(
                fontSize: 38.sp,
                color: ColorConstant.ffda44,
              ),
            ),
            TextSpan(
              text: '$money0',
              style: TextStyleConstant().white_70,
            ),
            TextSpan(
              text: '.$money1',
              style: TextStyleConstant().white_40,
            ),
          ])),
        ],
      ),
    );
  }

  //优惠金额
  Widget discountAmount(num) {
    String money = (AmountUtil.price2String((num) ?? 0, isFull: true));

    String money1 = '00';
    String money0 = money.split(".")[0];
    if (money.split('.').length > 1) {
      money1 = money.split(".")[1];
    }

    return Container(
      child: RichText(
          text: TextSpan(children: <TextSpan>[
        TextSpan(
          text: '$money0',
          style: TextStyleConstant().white_36,
        ),
        TextSpan(
          text: '${money1 == '00' ? '' : '.' + '$money1'}',
          style: TextStyleConstant().white_20,
        ),
      ])),
    );
  }

  Widget blueTitle() {
    return ClipRRect(
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(
            14.w,
          ),
        ),
        padding: EdgeInsets.symmetric(
          horizontal: 28.w,
        ),
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            BaseImage(
              '${"assets/image/eport_form_clerks_cashier.png"}',
              width: double.infinity,
            ),
            Positioned(
              child: Column(
                children: <Widget>[
                  Text(
                    "实收金额/元",
                    style: TextStyleConstant().white_28,
                  ),
                  SizedBox(
                    height: 12.w,
                  ),
                  totalInComeAmount(),
                  SizedBox(
                    height: 36.w,
                  ),
                  blueTitleBottomItem(),
                  SizedBox(
                    height: 2.w,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  //2个折叠 acceptData
  Widget twoFoldItem(int i) {
    return InkWell(
      onTap: () {
        if (i == 0) {
          boolFold0 = !boolFold0;
        }
        if (i == 1) {
          boolFold1 = !boolFold1;
        }
        setState(() {});
      },
      child: Container(
        decoration: BoxDecoration(
            border: Border(
                bottom: BorderSide(
          width: 1.px,
          color: ColorConstant.e6e6,
        ))),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              height: 90.w,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  RichText(
                    text: TextSpan(children: <TextSpan>[
                      TextSpan(
                        text: '    ${i == 0 ? '实收组成' : '优惠组成'}：',
                        style: TextStyleConstant().normal_2_28,
                      ),
                      TextSpan(
                        text: '${acceptData == null ? 0 : (i == 0 ? (acceptData["inComeList"].length ?? 0) : (acceptData["discountList"].length ?? 0))}种',
                        style: TextStyleConstant().normal_1_28,
                      ),
                    ]),
                  ),
                  BaseImage(
                    'assets/image/clerk_cashier_${(i == 0 ? boolFold0 : boolFold1) ? 'up' : 'down'}.png',
                    width: 26.w,
                    height: 16.w,
                  ),
                ],
              ),
            ),
            if ((i == 0 ? boolFold0 : boolFold1))
              SizedBox(
                height: 20.w,
              ),
            (i == 0 ? boolFold0 : boolFold1)
                ? Column(
                    children: (acceptData == null ? [] : ((acceptData[i == 0 ? "inComeList" : "discountList"])))
                        .map<Widget>((str) => Container(
                              padding: EdgeInsets.only(
                                top: 12.w,
                                bottom: 12.w,
                              ),
                              child: Row(
                                children: <Widget>[
                                  Expanded(
                                    flex: 2,
                                    child: Text(
                                      "${str["itemName"] == '' ? '--' : (str["itemName"] ?? '--')}：",
                                      textAlign: TextAlign.end,
                                      style: TextStyleConstant().normal_2_26,
                                    ),
                                  ),
                                  Expanded(
                                    flex: 3,
                                    child: Text(
                                      "￥${AmountUtil.price2String((str["itemAmount"]) ?? 0)}",
                                      style: TextStyleConstant().normal_1_26,
                                    ),
                                  ),
                                ],
                              ),
                            ))
                        .toList(),
                  )
                : Container(),
          ],
        ),
      ),
    );
  }

  Widget twoFold() {
    return Container(
      padding: EdgeInsets.symmetric(
        horizontal: 28.w,
      ),
      child: Column(
        children: <Widget>[
          twoFoldItem(0),
          twoFoldItem(1),
        ],
      ),
    );
  }

  //数据表格
  Widget TableCol(String title) {
    return Container(
      padding: EdgeInsets.symmetric(
        vertical: 22.w,
      ),
      child: Center(
        child: Text(
          "$title",
          style: TextStyleConstant().normal_2_28,
        ),
      ),
    );
  }

  Widget TableDataCol(dynamic v) {
    return v is Widget
        ? v
        : Container(
            padding: EdgeInsets.symmetric(
              vertical: 22.w,
            ),
            child: Center(
              child: Text(
                "$v",
                style: TextStyleConstant().normal_1_28,
              ),
            ),
          );
  }

  List<TableRow> dataTableTableRow() {
    return (tableData ?? [])
        .asMap()
        .keys
        .map(
          (i) => TableRow(
              decoration: BoxDecoration(
                  border: Border(
                      bottom: ((i + 1) == tableData.length)
                          ? BorderSide(width: 0, color: Colors.transparent)
                          : BorderSide(
                              width: 1.px,
                              color: ColorConstant.e6e6,
                            ))),
              children: [
                TableDataCol("${tableData[i]["waiterName"] == '' ? '--' : (tableData[i]["waiterName"] ?? '--')}"),
                TableDataCol("${tableData[i]["orderCount"] ?? '--'}"),
                TableDataCol("${tableData[i]["customerCount"] ?? '--'}"),
                TableDataCol(
                    "￥${AmountUtil.price2String((int.parse(((tableData[i]["totalAmount"] ?? 0) / tableData[i]["customerCount"]).toStringAsFixed(0))) ?? 0)}"),
                TableDataCol(
                    "￥${AmountUtil.price2String((int.parse(((tableData[i]["totalAmount"] ?? 0) / tableData[i]["orderCount"]).toStringAsFixed(0))) ?? 0)}"),
                TableDataCol("￥${AmountUtil.price2String((tableData[i]["totalAmount"]) ?? 0)}"),
                TableDataCol("￥${AmountUtil.price2String((tableData[i]["inComeAmount"]) ?? 0)}"),
                TableDataCol("￥${AmountUtil.price2String((tableData[i]["disCountAmount"]) ?? 0)}"),
                TableDataCol(
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: (tableData[i]["inComeList"] ?? [])
                        .map<Widget>((str) => Container(
                              padding: EdgeInsets.symmetric(vertical: 6.w, horizontal: 10.w),
                              child: RichText(
                                text: TextSpan(children: <TextSpan>[
                                  TextSpan(
                                    text: "${str["itemName"] ?? '--'}${(str["itemName"] == '' || str["itemName"] == null) ? '' : '元'}",
                                    style: TextStyleConstant().normal_1_26,
                                  ),
//                                      TextSpan(
//                                        text: '￥${AmountUtil.price2String((str["itemAmount"]) ?? 0, format: flustars.MoneyFormat.END_INTEGER)}',
//                                        style:TextStyleConstant().normal_2_26,
//                                      ),
                                ]),
                              ),
                            ))
                        .toList(),
                  ),
                ),
                TableDataCol(
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: (tableData[i]["discountList"] ?? [])
                        .map<Widget>((str) => Container(
                              padding: EdgeInsets.symmetric(vertical: 6.w, horizontal: 10.w),
                              child: RichText(
                                text: TextSpan(children: <TextSpan>[
                                  TextSpan(
                                    text: "${str["itemName"] ?? '--'}${(str["itemName"] == '' || str["itemName"] == null) ? '' : '元'}",
                                    style: TextStyleConstant().normal_1_26,
                                  ),
//                                      TextSpan(
//                                        text: '_￥${AmountUtil.price2String((str["itemAmount"]) ?? 0, format: flustars.MoneyFormat.END_INTEGER)}',
//                                        style:TextStyleConstant().normal_2_26,
//                                      ),
                                ]),
                              ),
                            ))
                        .toList(),
                  ),
                ),
              ]),
        )
        .toList();
  }

  Widget dataTable() {
    return Container(
      margin: EdgeInsets.only(
        top: 28.w,
        bottom: 28.w,
        left: 26.w,
        right: 26.w,
      ),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(
            14.w,
          ),
          boxShadow: [
            BoxShadow(
              color: ColorConstant.shadow,
              spreadRadius: 1.w,
              blurRadius: 9.w,
            )
          ],
        ),
        child: Container(
          padding: tableData.length == 0
              ? null
              : EdgeInsets.only(
                  bottom: 8.w,
                ),
          child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Column(
              children: <Widget>[
                Table(columnWidths: {
                  //列宽
                  0: FixedColumnWidth(86.0),
                  1: FixedColumnWidth(100.0),
                  2: FixedColumnWidth(100.0),
                  3: FixedColumnWidth(100.0),
                  4: FixedColumnWidth(100.0),
                  5: FixedColumnWidth(100.0),
                  6: FixedColumnWidth(100.0),
                  7: FixedColumnWidth(100.0),
                  8: FixedColumnWidth(180.0),
                  9: FixedColumnWidth(180.0),
                }, children: <TableRow>[
                  TableRow(
                      decoration: BoxDecoration(
                        color: Color.fromRGBO(245, 245, 245, 1),
                        borderRadius: BorderRadius.circular(
                          14.w,
                        ),
                      ),
                      children: [
                        TableCol("店员"),
                        TableCol('账单数'),
                        TableCol('客流'),
                        TableCol('人均消费'),
                        TableCol('单均消费'),
                        TableCol('订单金额'),
                        TableCol('实收金额'),
                        TableCol('优惠金额'),
                        TableCol('实收组成'),
                        TableCol('优惠组成'),
                      ]),
                  ...dataTableTableRow(),
                ]),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Future<Result<List<dynamic>>> _loadTask() async {
    Result.value([]);
  }

  Future<Result<List<dynamic>>> _refreshTask() async {
    var res = await api.statUserCashSumData(
      startTime: dateTime2String(startTime),
      endTime: dateTime2String(endTime),
    );
    if (res.successful()) {
      acceptData = res.data;
      tableData = (res.data["userCashVoList"] ?? []);

      boolFold0 = false;
      boolFold1 = false;
      setState(() {});
      return Result.value([1]);
    } else {
      toast(res.msg);
      return Result.value([1]);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(
              top: 26.w,
              bottom: 18.w,
              left: 20.w,
              right: 20.w,
            ),
            child: CalendarBar(
              startDateTime: startTime,
              endDateTime: endTime,
              onDateTimeChanged: (List<DateTime> dateTime) {
                startTime = dateTime[0];
                endTime = dateTime[1];
                loaderPullRefreshKey.currentState.refresh();
              },
              type: CalendarType.ymdhm,
            ),
          ),
          Expanded(
            child: LoaderPullRefresh<dynamic>(
                key: loaderPullRefreshKey,
                loadTask: _loadTask,
                refreshTask: _refreshTask,
                builder: (context) {
                  return SingleChildScrollView(
                    child: Column(
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Padding(
                              padding: EdgeInsets.only(
                                top: 0.w,
                                bottom: 10.w,
                                left: 20.w,
                                right: 20.w,
                              ),
                              child: Text(
                                "店员账单",
                                style: TextStyleConstant().normal_1_36,
                              ),
                            ),
                          ],
                        ),
                        blueTitle(),
                        twoFold(),
                        dataTable(),
                      ],
                    ),
                  );
                }),
          ),
        ],
      ),
    );
  }
}
